package cn.com.cloudpioneer.evaluate.controller;

import cn.com.cloudpioneer.evaluate.mapper.UserMapper;
import cn.com.cloudpioneer.evaluate.model.UserModel;
import cn.com.cloudpioneer.evaluate.service.RedisService;
import cn.com.cloudpioneer.evaluate.utils.CustomException;
import cn.com.cloudpioneer.evaluate.utils.JwtUtils;
import cn.com.cloudpioneer.evaluate.utils.StringUtil;
import cn.com.cloudpioneer.evaluate.utils.Values;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @auther maruikai
 * @create 2023/9/25-10:11
 */
@RestController
public class BaseController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @Autowired
    private RedisService redisService;

    @Resource
    private UserMapper userMapper;

    public UserModel verifyLogin() throws CustomException {

        String token = request.getHeader("token");
        if (StringUtil.isEmpty(token)) {
            response.setStatus(401);
            throw new CustomException(401, "获取用户信息异常");
        }
        String tokenKey = "evaluate:user:token::" + token;
        String userToken = String.valueOf(redisService.objectGet(tokenKey));
        if (StringUtil.isEmpty(userToken) || userToken.equals("null")) {
            response.setStatus(401);
            throw new CustomException(401, "登录超时");
        }
        String userId = JwtUtils.getUserId(userToken);
        UserModel byUserId = userMapper.findByUserId(userId);
        if (byUserId == null) {
            response.setStatus(401);
            throw new CustomException(401, "获取用户信息异常");
        }
        this.lengthenToken(tokenKey);
        return byUserId;
    }

    private void lengthenToken(String token) {
        redisService.expireKey(token, Values.EXPIRE_TIME);
    }

}
